package cn.leida.ruoyi.common.core.page;

import cn.hutool.core.util.StrUtil;
import lombok.Data;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

/**
 * 分页数据
 *
 * @author ruoyi
 */
@Data
public class PageDomain {

    public final static int DEFAULT_PAGE_NO = 0;
    public final static int DEFAULT_PAGE_SIZE = 10;

    /**
     * 当前记录起始索引
     */
    private Integer pageNum = DEFAULT_PAGE_NO;


    /**
     * 每页显示记录数
     */
    private Integer pageSize = DEFAULT_PAGE_SIZE;

    /**
     * 排序列
     */
    private String orderByColumn;

    /**
     * 排序的方向desc或者asc
     * asc: 顺序 (默认)
     * desc: 倒序
     */
    private String isAsc = "asc";

    public String getOrderBy() {
        if (StrUtil.isEmpty(orderByColumn)) {
            return "";
        }
        //驼峰转下划线命名
        return StrUtil.toUnderlineCase(orderByColumn) + " " + isAsc;
    }

    public int pageSize() {
        if (pageSize == null || pageSize <= 0) {
            return DEFAULT_PAGE_SIZE;
        }
        return pageSize;
    }


    public Sort sort(String defColumn) {
        // asc
        if (sortAsc()) {
            return Sort.by(Sort.Order.asc(column(defColumn)));
        }
        // desc
        return Sort.by(Sort.Order.desc(column(defColumn)));
    }

    private boolean sortAsc() {
        // asc
        if (StrUtil.equalsIgnoreCase(isAsc, Sort.Direction.ASC.name())) {
            return true;
        }
        // desc
        return false;
    }

    private String column(String defColumn) {
        if (StrUtil.isNotEmpty(orderByColumn)) {
            return orderByColumn;
        }
        return defColumn;
    }

    /**
     * 排序方式: 倒序
     */
    public Sort sortDesc(String defColumn) {
        if (sortAsc()) {
            return Sort.by(Sort.Order.asc(column(defColumn)));
        }
        return Sort.by(Sort.Order.desc(column(defColumn)));
    }

    /**
     * 排序方式: 顺序
     */
    public Sort sortAsc(String defColumn) {
        if (!sortAsc()) {
            return Sort.by(Sort.Order.desc(column(defColumn)));
        }
        return Sort.by(Sort.Order.asc(column(defColumn)));
    }


    public Integer pageNo() {
        return this.pageNum == null || this.pageNum <= 0 ? DEFAULT_PAGE_NO : this.pageNum - 1;
    }

    public Pageable pageSort(String defColumn) {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        return PageRequest.of(pageDomain.pageNo(), pageDomain.pageSize(), pageDomain.sort(defColumn));
    }

    public Pageable pageSortDesc(String defColumn) {
        return PageRequest.of(pageNo(), pageSize(), sortDesc(defColumn));
    }


}
